import type { Router } from 'vue-router';

import type { Menu } from '../types';

import { AuthModeEnum } from '@/enums/appEnum';
import { useAppStoreWithOut } from '@/store/modules/app';
import { useAuthStoreWithOut } from '@/store/modules/auth';

import { configureDynamicParamsMenu } from '../helper/menu';

export function createParamMenuGuard(router: Router) {
  const authStore = useAuthStoreWithOut();
  router.beforeEach(async (to, _, next) => {
    // filter no name route
    if (!to.name) {
      next();
      return;
    }

    // menu has been built.
    if (!authStore.getIsDynamicAddedRoute) {
      next();
      return;
    }

    let menus: Menu[] = [];
    if (isBackMode()) {
      menus = authStore.getBackMenuList;
    } else if (isRouteMappingMode()) {
      menus = authStore.getFrontMenuList;
    }
    menus.forEach((item) => configureDynamicParamsMenu(item, to.params));

    next();
  });
}

const getAuthMode = () => {
  const appStore = useAppStoreWithOut();
  return appStore.getProjectConfig.authMode;
};

const isBackMode = () => {
  return getAuthMode() === AuthModeEnum.BACK;
};

const isRouteMappingMode = () => {
  return getAuthMode() === AuthModeEnum.ROUTE_MAPPING;
};
